import { get, post, put, del } from '@/utils/request'
import { API_ENDPOINTS, replaceUrlParams } from '@/config/api'

/**
 * 统计分析API
 */

// 获取统计概览数据
export function getStatisticsOverview(params = {}) {
  return get(API_ENDPOINTS.STATISTICS.OVERVIEW, {
    timeRange: params.timeRange || 'month',
    startDate: params.startDate || '',
    endDate: params.endDate || ''
  })
}

// 获取订单统计数据
export function getOrderStatistics(params = {}) {
  return get(API_ENDPOINTS.STATISTICS.ORDERS, {
    timeRange: params.timeRange || 'month',
    groupBy: params.groupBy || 'day',
    serviceType: params.serviceType || '',
    region: params.region || '',
    startDate: params.startDate || '',
    endDate: params.endDate || ''
  })
}

// 获取收入统计数据
export function getRevenueStatistics(params = {}) {
  return get(API_ENDPOINTS.STATISTICS.REVENUE, {
    timeRange: params.timeRange || 'month',
    groupBy: params.groupBy || 'day',
    serviceType: params.serviceType || '',
    region: params.region || '',
    startDate: params.startDate || '',
    endDate: params.endDate || ''
  })
}

// 获取服务统计数据
export function getServiceStatistics(params = {}) {
  return get(API_ENDPOINTS.STATISTICS.SERVICES, {
    timeRange: params.timeRange || 'month',
    sortBy: params.sortBy || 'orders',
    sortOrder: params.sortOrder || 'desc'
  })
}

// 获取客户统计数据
export function getCustomerStatistics(params = {}) {
  return get(API_ENDPOINTS.STATISTICS.CUSTOMERS, {
    timeRange: params.timeRange || 'month',
    groupBy: params.groupBy || 'day',
    region: params.region || '',
    startDate: params.startDate || '',
    endDate: params.endDate || ''
  })
}

// 获取趋势分析数据
export function getTrendAnalysis(params = {}) {
  return get(API_ENDPOINTS.STATISTICS.TRENDS, {
    metric: params.metric || 'orders',
    timeRange: params.timeRange || 'month',
    granularity: params.granularity || 'day',
    compareWith: params.compareWith || 'previous_period'
  })
}

// 获取地区统计数据
export function getRegionStatistics(params = {}) {
  return get('/statistics/regions', {
    timeRange: params.timeRange || 'month',
    sortBy: params.sortBy || 'orders',
    sortOrder: params.sortOrder || 'desc',
    limit: params.limit || 10
  })
}

// 获取时间段分析数据
export function getTimeAnalysis(params = {}) {
  return get('/statistics/time-analysis', {
    timeRange: params.timeRange || 'month',
    metric: params.metric || 'orders',
    granularity: params.granularity || 'hour'
  })
}

// 获取服务类型分析数据
export function getServiceTypeAnalysis(params = {}) {
  return get('/statistics/service-types', {
    timeRange: params.timeRange || 'month',
    metric: params.metric || 'orders'
  })
}

// 获取客户满意度统计
export function getSatisfactionStatistics(params = {}) {
  return get('/statistics/satisfaction', {
    timeRange: params.timeRange || 'month',
    groupBy: params.groupBy || 'day',
    serviceType: params.serviceType || '',
    region: params.region || ''
  })
}

// 获取运营效率统计
export function getOperationEfficiency(params = {}) {
  return get('/statistics/operation-efficiency', {
    timeRange: params.timeRange || 'month',
    metric: params.metric || 'processing_time'
  })
}

// 获取竞争分析数据
export function getCompetitiveAnalysis(params = {}) {
  return get('/statistics/competitive-analysis', {
    timeRange: params.timeRange || 'month',
    region: params.region || '',
    serviceType: params.serviceType || ''
  })
}

// 导出统计数据
export function exportStatisticsData(params = {}) {
  return get('/statistics/export', {
    type: params.type || 'overview',
    timeRange: params.timeRange || 'month',
    format: params.format || 'excel',
    startDate: params.startDate || '',
    endDate: params.endDate || ''
  }, {
    responseType: 'blob'
  })
}

// 获取实时数据
export function getRealTimeData() {
  return get('/statistics/realtime')
}

// 获取预测数据
export function getForecastData(params = {}) {
  return get('/statistics/forecast', {
    metric: params.metric || 'orders',
    period: params.period || 30,
    model: params.model || 'linear'
  })
}

// 时间范围枚举
export const TIME_RANGES = {
  TODAY: 'today',
  YESTERDAY: 'yesterday',
  WEEK: 'week',
  LAST_WEEK: 'last_week',
  MONTH: 'month',
  LAST_MONTH: 'last_month',
  QUARTER: 'quarter',
  LAST_QUARTER: 'last_quarter',
  YEAR: 'year',
  LAST_YEAR: 'last_year',
  CUSTOM: 'custom'
}

// 时间范围文本映射
export const TIME_RANGE_TEXT = {
  [TIME_RANGES.TODAY]: '今天',
  [TIME_RANGES.YESTERDAY]: '昨天',
  [TIME_RANGES.WEEK]: '本周',
  [TIME_RANGES.LAST_WEEK]: '上周',
  [TIME_RANGES.MONTH]: '本月',
  [TIME_RANGES.LAST_MONTH]: '上月',
  [TIME_RANGES.QUARTER]: '本季度',
  [TIME_RANGES.LAST_QUARTER]: '上季度',
  [TIME_RANGES.YEAR]: '今年',
  [TIME_RANGES.LAST_YEAR]: '去年',
  [TIME_RANGES.CUSTOM]: '自定义'
}

// 统计指标枚举
export const METRICS = {
  ORDERS: 'orders',
  REVENUE: 'revenue',
  CUSTOMERS: 'customers',
  SATISFACTION: 'satisfaction',
  PROCESSING_TIME: 'processing_time',
  COMPLETION_RATE: 'completion_rate',
  REFUND_RATE: 'refund_rate'
}

// 统计指标文本映射
export const METRIC_TEXT = {
  [METRICS.ORDERS]: '订单数量',
  [METRICS.REVENUE]: '收入金额',
  [METRICS.CUSTOMERS]: '客户数量',
  [METRICS.SATISFACTION]: '客户满意度',
  [METRICS.PROCESSING_TIME]: '处理时间',
  [METRICS.COMPLETION_RATE]: '完成率',
  [METRICS.REFUND_RATE]: '退款率'
}

// 分组方式枚举
export const GROUP_BY = {
  HOUR: 'hour',
  DAY: 'day',
  WEEK: 'week',
  MONTH: 'month',
  QUARTER: 'quarter',
  YEAR: 'year'
}

// 分组方式文本映射
export const GROUP_BY_TEXT = {
  [GROUP_BY.HOUR]: '按小时',
  [GROUP_BY.DAY]: '按天',
  [GROUP_BY.WEEK]: '按周',
  [GROUP_BY.MONTH]: '按月',
  [GROUP_BY.QUARTER]: '按季度',
  [GROUP_BY.YEAR]: '按年'
}

// 获取时间范围文本
export function getTimeRangeText(timeRange) {
  return TIME_RANGE_TEXT[timeRange] || '未知'
}

// 获取指标文本
export function getMetricText(metric) {
  return METRIC_TEXT[metric] || '未知指标'
}

// 获取分组方式文本
export function getGroupByText(groupBy) {
  return GROUP_BY_TEXT[groupBy] || '未知分组'
}

// 格式化金额
export function formatMoney(amount) {
  if (typeof amount !== 'number') return '0'
  return amount.toLocaleString('zh-CN', {
    minimumFractionDigits: 0,
    maximumFractionDigits: 2
  })
}

// 格式化百分比
export function formatPercentage(value, decimals = 1) {
  if (typeof value !== 'number') return '0%'
  return `${value.toFixed(decimals)}%`
}

// 格式化趋势
export function formatTrend(value, showSign = true) {
  if (typeof value !== 'number') return '0%'
  const sign = showSign && value > 0 ? '+' : ''
  return `${sign}${value.toFixed(1)}%`
}

// 计算增长率
export function calculateGrowthRate(current, previous) {
  if (!previous || previous === 0) return 0
  return ((current - previous) / previous) * 100
}

// 计算平均值
export function calculateAverage(values) {
  if (!Array.isArray(values) || values.length === 0) return 0
  const sum = values.reduce((acc, val) => acc + (val || 0), 0)
  return sum / values.length
}

// 获取趋势方向
export function getTrendDirection(value) {
  if (value > 0) return 'up'
  if (value < 0) return 'down'
  return 'stable'
}

// 获取趋势图标
export function getTrendIcon(value) {
  if (value > 0) return '↗'
  if (value < 0) return '↘'
  return '→'
}

// 获取趋势颜色
export function getTrendColor(value) {
  if (value > 0) return 'success'
  if (value < 0) return 'danger'
  return 'info'
}

// 创建统计数据对象
export function createStatisticsData(data) {
  return {
    id: data.id || null,
    metric: data.metric || '',
    value: data.value || 0,
    previousValue: data.previousValue || 0,
    trend: data.trend || 0,
    timeRange: data.timeRange || TIME_RANGES.MONTH,
    date: data.date || new Date().toISOString(),
    region: data.region || '',
    serviceType: data.serviceType || '',
    extra: data.extra || {}
  }
}

// 验证统计参数
export function validateStatisticsParams(params) {
  const errors = []
  
  if (params.timeRange && !Object.values(TIME_RANGES).includes(params.timeRange)) {
    errors.push('无效的时间范围')
  }
  
  if (params.metric && !Object.values(METRICS).includes(params.metric)) {
    errors.push('无效的统计指标')
  }
  
  if (params.groupBy && !Object.values(GROUP_BY).includes(params.groupBy)) {
    errors.push('无效的分组方式')
  }
  
  if (params.startDate && params.endDate) {
    const start = new Date(params.startDate)
    const end = new Date(params.endDate)
    if (start >= end) {
      errors.push('开始时间必须早于结束时间')
    }
  }
  
  return {
    valid: errors.length === 0,
    errors
  }
}
